﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using pb;

namespace AppMain
{
    struct MsgInfo
    {
        public NetRole role;
        public PBMessage msg;
    }

    public class ProtocolEventMgr : Singleton<ProtocolEventMgr>
    {
        private Dictionary<short, Action<NetRole, PBMessage>> protocolMap = null;
        private Queue<MsgInfo> queue = new Queue<MsgInfo>();
        protected override void initialize()
        {
            protocolMap = new Dictionary<short, Action<NetRole, PBMessage>>();
        }

        public void addListener(short cmd, Action<NetRole, PBMessage> handler)
        {
            protocolMap.Add(cmd, handler);
        }

        public void tick()
        {
            int count = queue.Count;
            count = count / 2 + 1;
            while (count > 0 && queue.Count > 0)
            {
                count--;
                MsgInfo info = queue.Dequeue();

                short cmd = info.msg.cmd;
                Action<NetRole, PBMessage> action;
                if (protocolMap.TryGetValue(cmd, out action))
                {
                    action.Invoke(info.role, info.msg);
                }
            }
        }

        public void dispatch(NetRole role, PBMessage msg)
        {
            MsgInfo info = new MsgInfo();
            info.role = role;
            info.msg = msg;
            queue.Enqueue(info);
        }

    }

}
